extends CanvasLayer

@onready var mush_room: StaticBody2D = %MushRoom
@onready var jim: StaticBody2D = %Jim
@onready var skeleton: StaticBody2D = %Skeleton
@onready var goblin: StaticBody2D = %Goblin
@onready var knight: StaticBody2D = %Knight
@onready var wizard: StaticBody2D = %Wizard

@onready var players: Array = [mush_room, jim, skeleton]
@onready var enemies: Array = [goblin, knight, wizard]

var small_turn_count: int = 0
var turn_count: int = 0
const NULL_POSITION: int = -1

func _ready() -> void:
	await get_tree().create_timer(1).timeout
	Engine.time_scale = 1
	Events.signal_player_turn.connect(_player_turn)
	Events.signal_enemy_turn.connect(_enemy_turn)
	_player_turn()

func _process(_delta: float) -> void:
	pass

func _player_turn() -> void:
	if small_turn_count == players.size() + enemies.size():
		reset_is_current_turn_played(players, enemies)
		small_turn_count = 0
	var player: StaticBody2D = get_current_play_sprites(players)
	small_turn_count += 1
	if player != null:
		player.turn(players, enemies)
	else:
		_enemy_turn()
		

func _enemy_turn() -> void:
	if small_turn_count == players.size() + enemies.size():
		reset_is_current_turn_played(players, enemies)
		small_turn_count = 0
	var enemy: StaticBody2D = get_current_play_sprites(enemies)
	small_turn_count += 1
	if enemy != null:
		enemy.turn(enemies, players)
	else: 
		_player_turn() 

func get_current_play_sprites(array: Array) -> StaticBody2D:
	var valid_sprites := []
	# 过滤出符合条件的精灵
	for sprite in array:
		if sprite.health > 0 && !sprite.is_current_turn_played:
			valid_sprites.append(sprite)
	# 如果没有符合条件的精灵，返回 null
	if valid_sprites.size() == 0:
		return null
	# 冒泡排序：按 physical_position 从小到大排序
	for i in range(valid_sprites.size()):
		for j in range(0, valid_sprites.size() - i - 1):
			if valid_sprites[j].physical_position > valid_sprites[j + 1].physical_position:
				var temp: StaticBody2D = valid_sprites[j]
				valid_sprites[j] = valid_sprites[j + 1]
				valid_sprites[j + 1] = temp
	# 返回第一个元素（physical_position 最小）
	return valid_sprites[0]
	
func reset_is_current_turn_played(reset_players: Array, reset_enemies: Array) -> void:
	var all_acted := true
	# 检查 player 组
	for sprite in reset_players:
		if !sprite.is_current_turn_played and sprite.health > 0:
			all_acted = false
			break  # 只要有一个没出手，就不用继续检查了
	# 如果 player 中还有未出手的，就不检查敌人了
	if !all_acted:
		return
	# 检查 enemies 组
	for sprite in reset_enemies:
		if !sprite.is_current_turn_played and sprite.health > 0:
			all_acted = false
			break
	# 如果全部都出手了，就重置 is_current_turn_played
	if all_acted:
		for sprite in reset_players:
			sprite.is_current_turn_played = false
		for sprite in reset_enemies:
			sprite.is_current_turn_played = false
	
	
